<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input v-model="listQuery.username" style="width: 200px;" class="filter-item" placeholder="请输入用户名称" @keyup.enter.native="handleFilter"/>
      <el-input v-model="listQuery.phone" style="width: 200px;" class="filter-item" placeholder="请输入电话" @keyup.enter.native="handleFilter"/>
      <el-input v-model="listQuery.identification" style="width: 200px;" class="filter-item" placeholder="请输入身份证" @keyup.enter.native="handleFilter"/>
      <el-button v-if="this.btn_query" v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button v-if="this.btn_add" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%">
      <el-table-column width="100" align="center" label="证件照片">
        <template slot-scope="scope">
          <img :src="scope.row.imageurl" style="height:auto;width:100%;">
        </template>
      </el-table-column>
      <el-table-column width="120" align="center" label="员工名称">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" align="center" label="联系电话">
        <template slot-scope="scope">
          <span>{{ scope.row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column width="170" align="center" label="身份证号">
        <template slot-scope="scope">
          <span>{{ scope.row.identification }}</span>
        </template>
      </el-table-column>
      <el-table-column width="160" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{ dformat("yyyy-MM-dd hh:mm:ss",scope.row.createtime) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="160" align="center" label="更新时间">
        <template slot-scope="scope">
          <span>{{ dformat("yyyy-MM-dd hh:mm:ss",scope.row.updatetime) }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.actions')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="btn_edit" type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button v-if="btn_delete" size="mini" type="danger" @click="handleDelete(scope.row)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        :current-page.sync="listQuery.page"
        :page-sizes="[10,20,30, 50]"
        :page-size="listQuery.limit"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>
    <div v-if="dialogFormVisible">
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">
          <el-form-item label="员工名称" prop="username">
            <el-input v-model="temp.username"/>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="temp.phone"/>
          </el-form-item>
          <el-form-item label="身份证号" prop="identification">
            <el-input v-model="temp.identification"/>
          </el-form-item>
          <el-form-item label="证件照片" prop="imageurl">
            <el-input v-model="temp.imageurl" class="imageinput"/>
            <el-button size="medium" type="primary" class="uploadbutton" @click="activeTrigger">点击上传</el-button>
            <el-upload
              ref="uploadTool"
              class="upload-demo"
              action=""
              :limit="1"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :http-request="getUploadAddress"
              list-type="picture">
              <button style="display: none" id="trigger"></button>
            </el-upload>
          </el-form-item>
          <el-form-item label="是否变动设备" prop="ismodifydevice">
            <el-radio
              v-for="item in yesOrNot"
              :key="item.id"
              v-model="temp.ismodifydevice"
              :label="item.value">
              {{ item.value }}
            </el-radio>
          </el-form-item>
          <el-form-item label="是否变动资产" prop="ismodifyaccet">
            <el-radio
              v-for="item in yesOrNot"
              :key="item.id"
              v-model="temp.ismodifyaccet"
              :label="item.value">
              {{ item.value }}
            </el-radio>
          </el-form-item>
          <el-form-item label="是否变动站点" prop="ismodifysite">
            <el-radio
              v-for="item in yesOrNot"
              :key="item.id"
              v-model="temp.ismodifysite"
              :label="item.value">
              {{ item.value }}
            </el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
          <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{ $t('table.confirm') }}</el-button>
          <el-button v-else type="primary" @click="updateData">{{ $t('table.confirm') }}</el-button>
        </div>
      </el-dialog>
    </div>

  </div>
</template>

<script>
  import { getMatUserList, addMatUser, updateMatUser,deleteMatUser } from '@/api/fire/maintainor/user'
  import { uploadPic } from '@/api/fire/proprietor/monitor'
  import { getAuthority } from '@/api/fire/proprietor/user'
  import { dateFormat } from '@/utils/dateFormatter'
  import { isNotNull, length, selectvalidator } from '@/utils/validate'
  import waves from '@/directive/waves' // 水波纹指令

  export default {
    name: 'maintainoruser',
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      }
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          username:'',
          phone:'',
          identification:''
        },
        showReviewer: false,
        temp: {
          userid:'',
          username: '',
          phone: '',
          identification: '',
          imageurl: '',
          ismodifydevice: '',
          ismodifyaccet: '',
          ismodifysite: ''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑员工',
          create: '创建员工'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          username: isNotNull('请输入用户名'),
          phone: isNotNull('请输入手机号码').concat(selectvalidator('validatePhone')),
          identification: isNotNull('请输入身份证').concat(selectvalidator('validateIdNo')),
        },
        dialogFormRolesVisible: false,
        btn_query: false,
        btn_add: false,
        btn_edit: false,
        btn_delete: false,
        yesOrNot:[{id:1,value:"YES"},{id:2,value:"NO"}],
        fileList: []
      }
    },
    created() {
      this.getList();
      this.btn_query = this.checkPermission(['maintainor:user:list']);
      this.btn_add = this.checkPermission(['maintainor:user:add']);
      this.btn_edit = this.checkPermission(['maintainor:user:update']);
      this.btn_delete = this.checkPermission(['maintainor:user:delete']);
    },
    methods: {
      getList() {
        this.listLoading = true
        getMatUserList(this.listQuery).then(response => {
          this.list = response.data.context.records
          for(let index in this.list){
            getAuthority(this.list[index].userid).then(response => {
              this.list[index].ismodifydevice = response.data.context.ismodifydevice
              this.list[index].ismodifyaccet = response.data.context.ismodifyaccet
              this.list[index].ismodifysite = response.data.context.ismodifysite
            })
          }
          this.total = response.data.context.total
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      resetTemp() {
        this.temp = {
          userid:'',
          username: '',
          phone: '',
          identification: '',
          commanyphone: '',
          imageurl: '',
          ismodifydevice: 'NO',
          ismodifyaccet: 'NO',
          ismodifysite: 'NO'
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            addMatUser(this.temp).then(response => {
              if (response.data.status === '0') {
                this.dialogFormVisible = false
                this.getList()
                this.$notify({
                  title: '成功',
                  message: response.data.message,
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify.error({
                  title: '失败',
                  message: response.data.message,
                  duration: 2000
                })
              }
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            updateMatUser(tempData).then(response => {
              if (response.data.status === '0') {
                this.dialogFormVisible = false
                this.getList()
                this.$notify({
                  title: '成功',
                  message: response.data.message,
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify.error({
                  title: '失败',
                  message: response.data.message,
                  duration: 2000
                })
              }
            })
          }
        })
      },
      handleDelete(row) {
        this.$confirm("此操作将永久删除, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          deleteMatUser(row.userid).then(response => {
            if (response.data.status === '0') {
              this.getList()
              this.$notify({
                title: '成功',
                message: response.data.msg,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify.error({
                title: '失败',
                message: response.data.msg,
                duration: 2000
              })
            }
          })
        })

      },
      dformat(fmt, date) {
        return dateFormat(fmt, date)
      },
      getUploadAddress(param){
        const formData = new FormData()
        formData.append('file',param.file, param.file.name)
        uploadPic(formData).then(response=>{
          this.temp.imageurl = response.data.context
        })
      },
      handlePreview(file){
        console.log(file)
      },
      handleRemove(file, fileList){
        this.temp.imageurl = ''
      },
      activeTrigger(){
        document.getElementById("trigger").click();
      },
    }
  }
</script>
<style>
  .imageinput{
    width: 73%;
    display: inline-block;
  }
  .uploadbutton{
    width: 25%;
    display: inline-block;
    padding: 10px 0px;
  }
  .el-upload{
    display: none;
  }
</style>
